<template>
  <div class="app-container">
    <el-dialog :title="title" :visible.sync="visible" width="500px" v-if="visible" append-to-body
      :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" :disabled="disabled">
        <div v-if="type==1">
          <el-form-item label="" prop="">
            <el-upload class="upload-demo" :action="fileaction" :headers="headers" :data="fileData" :limit="1"
              :on-success="handleFileChange" :show-file-list="true" :file-list="fileList" :on-remove="onRemove">
              <el-button type="primary" size="small" icon="el-icon-plus">添加文件</el-button>
              <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
          </el-form-item>
          <div v-if="importInfo.total">添加成功，新增{{importInfo.total}}奖品数量</div>
        </div>
        <div v-if="type==2">
          <div style="margin-bottom: 20px">是否添加{{equityName}}权益券码数量</div>
          <el-form-item label="添加数量" prop="addNum">
            <el-input v-model="form.addNum" placeholder="请输入" :style="{width: inputWidth}">
            </el-input>
            <span style="margin-left: 10px">(添加时限量最多1000个)</span>
          </el-form-item>
        </div>
        <div class="bottom_box">
          <el-button type="primary" size="small" @click="saveClick" :loading="sumitLoading" :disabled="sumitDisabled"
            v-if="type==1">保存
          </el-button>
          <el-button type="primary" size="small" @click="saveClickTwo('form')" :loading="sumitLoading" v-if="type==2">确认添加
          </el-button>
          <el-button @click="visible=false" size="small">取消</el-button>
        </div>
      </el-form>
      <!-- 导入失败弹窗 -->
      <el-dialog title="导入失败" :visible.sync="dialogVisible" width="500" append-to-body>
        <div>{{importMessage}}</div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getToken
  } from "@/utils/auth";
  import {
    inventoryCouponCodeSave,
    couponCodeAdd
  } from "@/api/equityManager/equityInventory";
  import ExportExcelButton from "@/components/ExportExcelButton/index";
  export default {
    // dicts: ['asset_card_type'],
    name: "dialogwhiteList",
    components: {
      ExportExcelButton,
    },
    data() {
      var checkAddNum = (rule, value, callback) => { //
        let regNumber = /^\+?[1-9]\d*$/; //大于0的正整数
        // console.log(value, this.ruleForm.couponValidityType)
        if (!value) {
          return callback(new Error('请输入'));
        } else if (regNumber.test(value) == false) {
          return callback(new Error('请输入大于0正整数'));
        } else {
          return callback()
        }
      };
      return {
        labelWidth: '120px',
        inputWidth: '200px',
        sumitLoading: false,
        sumitDisabled: true,
        dialogVisible: false, //导入失败弹窗
        importMessage: '', //导入失败原因
        id: '', //
        loading: false,
        addLoading: false,
        // 导入所需参数
        fileData: {
          id: ''
        },
        type: '1', // 1:导入券码  2：系统生成
        equityName: '', //权益名称
        fileList: [],
        fileaction: process.env.VUE_APP_BASE_API + "/equity/inventory/coupon/code/import",
        headers: {
          "X-Access-Token": getToken(),
        }, //设置上传文件请求头
        importInfo: {}, //导入结果
        // 是否禁用表单
        disabled: false,
        // 弹出层标题
        title: "添加券码",
        // 是否显示弹出层
        visible: false,
        // 表单参数(系统生成状态下)
        form: {
          addNum: '', //新增数量
        },
        // 表单校验
        rules: {
          addNum: [{
            required: true,
            validator: checkAddNum,
            trigger: ['blur', 'change'],
          }],
        },
      };
    },
    created() {

    },
    computed: {},
    methods: {
      /** 弹窗 */
      open(row) {
        this.importInfo = {}
        this.sumitDisabled = true
        this.fileData.id = row.id
        this.type = row.type
        this.equityName = row.name
        this.form.addNum = ''
        this.visible = true
      },
      // 取消按钮
      cancel() {
        this.visible = false;
      },
      //导入文件
      handleFileChange(res, file) {
        console.log('文件', res, file)
        if (res.code == 200) {
          this.$message.success('添加成功');
          this.importInfo = res.result
          this.sumitDisabled = false
        } else {
          // this.$message.error(res.message);
          this.importMessage = res.message
          this.dialogVisible = true
          this.sumitDisabled = true
          setTimeout(() => {
            this.fileList = []
          }, 800)
        }
      },
      //文件移除成功时
      onRemove() {
        this.fileList = []
        this.importInfo = {}
      },
      //保存（系统生成）
      saveClickTwo(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.sumitLoading = true
            let data = {
              id: this.fileData.id,
              addNum: this.form.addNum
            }
            couponCodeAdd(data).then(response => {
              this.$message.success('添加成功');
              this.cancel();
              this.$emit('refresh')
              this.sumitLoading = false
            }).catch(() => {
              this.sumitLoading = false
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      //保存(导入券码)
      saveClick() {
        this.sumitLoading = true
        let data = {
          id: this.fileData.id,
          ...this.importInfo
        }
        inventoryCouponCodeSave(data).then(response => {
          this.$message.success('保存成功');
          this.$emit('refresh')
          this.sumitLoading = false
          this.visible = false
        }).catch(() => {
          this.sumitLoading = false
        });
      },
    },
  };

</script>
<style scoped>
  .tabel_box_h {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-bottom: 10px;
  }

  .icon_yes {
    font-size: 30px;
    color: #67c23a;
  }

  .icon_no {
    font-size: 30px;
    color: #f56c6c;
  }

  .bottom_box {
    display: flex;
    justify-content: flex-end;
  }

</style>
